import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { requestUrl as url } from '../assets/js/config';
import 'rxjs/add/operator/toPromise';
import { isDevMode } from '@angular/core';
// 如何写成import模式呀
// import queryString from 'query-string';
const queryString = require('query-string');


let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let opts = new RequestOptions();
opts.headers = headers;

@Injectable()
export class HttpService {

  isLoading: boolean = false;

  constructor(private http: Http) { }

  post(data) {
    // if(isDevMode()) return Promise.resolve({success:false});
    this.isLoading = true;
    return this.http.post(url, queryString.stringify(data), opts).toPromise()
    .then(
      res => {
        this.isLoading = false;
        return res.json();
      },
      msg => {
        console.log(`Error: ${msg.status} ${msg.statusText}`);
        this.isLoading = false;
        alert('服务器紊乱了');
      }
    );
  }

  form(fm) {
    this.isLoading = true;
    return this.http.post(url, fm).toPromise()
    .then(
      res => {
        this.isLoading = false;
        return res.json();
      },
      msg => {
        console.log(`Error: ${msg.status} ${msg.statusText}`);
        this.isLoading = false;
        alert('服务器紊乱了');
      }
    );
  }

}
